package ar.com.ford.it.fullEconomics.view.form;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.apache.struts.validator.ValidatorForm;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;

public class PartForm extends ValidatorForm {
    private String section;
    private String name;
    private String prefixFind;
    private String baseFind;
    private String suffixFind;
    private String partClassFind;
    private String dateInMin;
    private String dateInMax;
    private String dateOutMin;
    private String dateOutMax;
    private String supplierClass;
    private String supplierCode;
    private String partClass;
    private String lowCom;
    private String prefix;
    private String base;
    private String suffix;
    private String unitsMesure;
    private String fechaIn;
    private String fechaOut;
    private String partCommodity;
    private Collection parts;
    private Teesp01Part partSelected;
    private String editBlocked;
    private String confirmCascadeDelete;
    private String showConfirmCascadeDelete;
    private String selectedRowNum;

    /**
     * Resetea el formulario
     * 
     */
    public void resetForm() {
        this.section = "";
        this.name = null;
        this.prefix = null;
        this.base = null;
        this.suffix = null;
        this.unitsMesure = null;
        this.fechaIn = null;
        this.fechaOut = null;
        this.editBlocked = "false";
        this.supplierCode = null;
        this.prefixFind = null;
        this.baseFind = null;
        this.suffixFind = null;
        this.dateInMin = null;
        this.dateInMax = null;
        this.dateOutMin = null;
        this.dateOutMax = null;
        this.parts = null;
        this.partClass = "C";
        this.lowCom = null;
        this.partClassFind = "F";
        this.supplierClass = "-1";
        this.partCommodity = "-1";
        this.confirmCascadeDelete = "false";
        this.showConfirmCascadeDelete = "false";
    }

    /**
     * Limpia los campos utilizados en el form para la creacion o actualizacion
     * de Parts
     * 
     */
    public void clearCreateUpdateFields() {
        this.name = null;
        this.prefix = null;
        this.base = null;
        this.suffix = null;
        this.unitsMesure = null;
        this.fechaIn = null;
        this.fechaOut = null;
        this.partClass = "C";
        this.lowCom = null;
        this.partCommodity = "-1";
        this.editBlocked = "false";
    }

    /**
     * Limpia los campos utilizados en el form para la busqueda
     * de Parts
     * 
     */
    public void clearFindFields() {
        this.supplierCode = null;
        this.prefixFind = null;
        this.baseFind = null;
        this.suffixFind = null;
        this.dateInMin = null;
        this.dateInMax = null;
        this.dateOutMin = null;
        this.dateOutMax = null;
        this.partClassFind = "-1";
        this.supplierClass = "-1";
    }

    /**
     * Setea el Part seleccionado para luego ser modificado
     * 
     * @param key
     * @param value
     */
    public void setEditMapped(String key, String value) {
        List parts = (List) this.getParts();

        this
                .setPartSelected((Teesp01Part) parts
                        .get(Integer.parseInt(key) - 1));
    }
    
    /**
     * Setea el Part seleccionado para luego ser modificado
     * 
     * @param key
     * @param value
     */
    public void setSeleccMapped(String key, String value) {
        List parts = (List) this.getParts();

        this
                .setPartSelected((Teesp01Part) parts
                        .get(Integer.parseInt(key) - 1));
    }
    
    /**
     * devuelve los keys de las parts seleccionadas. 
     * @param key
     * @return
     */
    public boolean getSeleccMapped(String key){
        return false;
    }

    /**
     * Setea el Part seleccionada para luego ser eliminado
     * 
     * @param key
     * @param value
     */
    public void setDeleteMapped(String key, String value) {
        setEditMapped(key, value);
    }

    /**
     * Setea los campos del cuadro de creacion/modificacion de Parts
     * 
     * @param part
     */
    public void setPartForEdit(Teesp01Part part) {

        Calendar calFechaIn = Calendar.getInstance();
        calFechaIn.setTime(part.getEesp01PartInDateY());
        Calendar calFechaOut = Calendar.getInstance();
        calFechaOut.setTime(part.getEesp01PartOutDateY());

        this.setName(part.getEesp01PartDescriptionX());
        this.setPrefix(part.getEesp01PartPrefixCodeC());
        this.setBase(part.getEesp01PartBaseCodeC());
        this.setSuffix(part.getEesp01PartSuffixCodeC());
        this.setLowCom(part.getEesp01PartCommodLowCodeC());
        this.setUnitsMesure(part.getEesp01PartUnitmeasureCodeC());
        this.setFechaIn(FullEconomicsDateUtil.format(calFechaIn));
        this.setFechaOut(FullEconomicsDateUtil.format(calFechaOut));
    }

    /**
     * Setea los campos del Part para su posterior creacion
     * 
     * @return Part con los campos minimos seteados para la posterior creacion
     */
    public Teesp01Part getPartForCreate() {
        Teesp01Part part = new Teesp01Part();
        Calendar fechaCalendarIn = FullEconomicsDateUtil.format(this
                .getFechaIn());
        Timestamp tsFechaIn = new Timestamp(fechaCalendarIn.getTimeInMillis());
        Calendar fechaCalendarOut = FullEconomicsDateUtil.format(this
                .getFechaOut());
        Timestamp tsFechaOut = new Timestamp(fechaCalendarOut.getTimeInMillis());

        part.setEesp01PartInDateY(tsFechaIn);
        part.setEesp01PartOutDateY(tsFechaOut);
        part.setEesp01PartPrefixCodeC(this.getPrefix());
        part.setEesp01PartBaseCodeC(this.getBase());
        part.setEesp01PartSuffixCodeC(this.getSuffix());
        part.setEesp01PartCommodLowCodeC(this.getLowCom());
        part.setEesp01PartClassCodeC("C");
        part.setEesp01PartUnitmeasureCodeC(this.getUnitsMesure());
        part.setEesp01PartDescriptionX(this.getName());
        part.setEesp01PartDescriptionBrX(this.getName());

        return part;
    }

    /**
     * Setea los campos del Part para su posterior actualizacion
     * 
     * @param part
     * Part a actualizar
     * @return Part con los campos a actualizar modificados
     */
    public Teesp01Part getPartForUpdate(Teesp01Part part) {

        Calendar fechaCalendarIn = FullEconomicsDateUtil.format(this
                .getFechaIn());
        Timestamp tsFechaIn = new Timestamp(fechaCalendarIn.getTimeInMillis());
        Calendar fechaCalendarOut = FullEconomicsDateUtil.format(this
                .getFechaOut());
        Timestamp tsFechaOut = new Timestamp(fechaCalendarOut.getTimeInMillis());

        part.setEesp01PartInDateY(tsFechaIn);
        part.setEesp01PartOutDateY(tsFechaOut);
        if(StringUtils.isBlank(this.getPrefix()))
            part.setEesp01PartPrefixCodeC(" ");
        else
            part.setEesp01PartPrefixCodeC(this.getPrefix());
        part.setEesp01PartBaseCodeC(this.getBase());
        if(StringUtils.isBlank(this.getSuffix()))
            part.setEesp01PartSuffixCodeC(" ");
        else
            part.setEesp01PartSuffixCodeC(this.getSuffix());
        part.setEesp01PartClassCodeC("C");
        part.setEesp01PartCommodLowCodeC(this.getLowCom());
        part.setEesp01PartUnitmeasureCodeC(this.getUnitsMesure());
        part.setEesp01PartDescriptionX(this.getName());
        part.setEesp01PartDescriptionBrX(this.getName());

        return part;
    }

    /**
     * Genera las validaciones necesarias.
     */
    public ActionErrors validate(ActionMapping mapping,
                                 HttpServletRequest request) {

        ActionErrors ae = new ActionErrors();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        if ("find".equalsIgnoreCase(this.getSection())) {
            if (!StringUtils.isBlank(this.getDateInMin())) {
                if (StringUtils.isBlank(this.getDateInMax())) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "part.error.invalidRange",
                                            resources
                                                    .getMessage("part.label.tableHeader.fechaIn")));
                }
                try {
                    if (FullEconomicsDateUtil.format(this.getDateInMin()) == null) {
                        ae.add(ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage("errors.date", this
                                        .getDateInMin()));
                    }
                } catch (Exception e) {
                    ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "errors.date", this.getDateInMin()));
                }
            }
            if (!StringUtils.isBlank(this.getDateInMax())) {
                if (StringUtils.isBlank(this.getDateInMin())) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "part.error.invalidRange",
                                            resources
                                                    .getMessage("part.label.tableHeader.fechaIn")));
                }
                try {
                    if (FullEconomicsDateUtil.format(this.getDateInMax()) == null) {
                        ae.add(ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage("errors.date", this
                                        .getDateInMax()));
                    }
                } catch (Exception e) {
                    ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "errors.date", this.getDateInMax()));
                }
            }
            if (!StringUtils.isBlank(this.getDateOutMin())) {
                if (StringUtils.isBlank(this.getDateOutMax())) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "part.error.invalidRange",
                                            resources
                                                    .getMessage("part.label.tableHeader.fechaOut")));
                }
                try {
                    if (FullEconomicsDateUtil.format(this.getDateOutMin()) == null) {
                        ae.add(ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage("errors.date", this
                                        .getDateOutMin()));
                    }
                } catch (Exception e) {
                    ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "errors.date", this.getDateOutMin()));
                }
            }
            if (!StringUtils.isBlank(this.getDateOutMax())) {
                if (StringUtils.isBlank(this.getDateOutMin())) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "part.error.invalidRange",
                                            resources
                                                    .getMessage("part.label.tableHeader.fechaOut")));
                }
                try {
                    if (FullEconomicsDateUtil.format(this.getDateOutMax()) == null) {
                        ae.add(ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage("errors.date", this
                                        .getDateOutMax()));
                    }
                } catch (Exception e) {
                    ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "errors.date", this.getDateOutMax()));
                }
            }
        }
        if ("createUpdate".equalsIgnoreCase(this.getSection())) {

            // Verifico el codigo que no este vacio
            if (StringUtils.isBlank(this.getName())) {
                ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "errors.required", resources
                                .getMessage("part.label.name")));
            }
            if (StringUtils.isBlank(this.getBase())) {
                ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "errors.required", resources
                                .getMessage("part.label.base")));
            }
            try {

                // Verifico y formateo la fechas In
                if (StringUtils.isBlank(this.getFechaIn())) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "errors.required",
                                            resources
                                                    .getMessage("part.label.tableHeader.fechaIn")));
                } else {
                    if (FullEconomicsDateUtil.format(this.getFechaIn()) == null) {
                        ae
                                .add(
                                        ActionMessages.GLOBAL_MESSAGE,
                                        new ActionMessage(
                                                "errors.date",
                                                resources
                                                        .getMessage("part.label.tableHeader.fechaIn")));
                    }
                }
            } catch (Exception e) {
                ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "errors.date", resources
                                .getMessage("part.label.tableHeader.fechaIn")));
            }

            try {
                // Verifico y formateo la fechas Out
                if (StringUtils.isBlank(this.getFechaOut())) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "errors.required",
                                            resources
                                                    .getMessage("part.label.tableHeader.fechaOut")));

                } else {
                    if (FullEconomicsDateUtil.format(this.getFechaOut()) == null) {
                        ae
                                .add(
                                        ActionMessages.GLOBAL_MESSAGE,
                                        new ActionMessage(
                                                "errors.date",
                                                resources
                                                        .getMessage("part.label.tableHeader.fechaOut")));
                    }
                }
            } catch (Exception e) {
                ae
                        .add(
                                ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage(
                                        "errors.date",
                                        resources
                                                .getMessage("part.label.tableHeader.fechaOut")));
            }

            // Si no hubo errores
            if (ae.size() == 0)
                // Verifico que la fecha de inicio sea menor a la fecha de fin
                if (FullEconomicsDateUtil.getDifference(this.getFechaIn(), this
                        .getFechaOut()) <= 0) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "errors.date.range",
                                            resources
                                                    .getMessage("part.label.tableHeader.fechaOut"),
                                            resources
                                                    .getMessage("part.label.tableHeader.fechaIn")));
                }
        }

        return ae;
    }

    public Collection getParts() {
        return parts;
    }

    public void setParts(Collection parts) {
        this.parts = parts;
    }

    public Teesp01Part getPartSelected() {
        return partSelected;
    }

    public void setPartSelected(Teesp01Part partSelected) {
        this.partSelected = partSelected;
    }

    public String getFechaIn() {
        return fechaIn;
    }

    public void setFechaIn(String fechaIn) {
        this.fechaIn = fechaIn;
    }

    public String getFechaOut() {
        return fechaOut;
    }

    public void setFechaOut(String fechaOut) {
        this.fechaOut = fechaOut;
    }

    public String getSection() {
        return section;
    }

    public void setSection(String section) {
        this.section = section;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name.toUpperCase();
    }

    public String getBase() {
        return base;
    }

    public void setBase(String base) {
        this.base = base.toUpperCase();
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix.toUpperCase();
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String sufix) {
        this.suffix = sufix.toUpperCase();
    }

    public String getBaseFind() {
        return baseFind;
    }

    public void setBaseFind(String baseFind) {
        this.baseFind = baseFind.toUpperCase();
    }

    public String getPrefixFind() {
        return prefixFind;
    }

    public void setPrefixFind(String prefixFind) {
        this.prefixFind = prefixFind.toUpperCase();
    }

    public String getSuffixFind() {
        return suffixFind;
    }

    public void setSuffixFind(String suffixFind) {
        this.suffixFind = suffixFind.toUpperCase();
    }

    public String getUnitsMesure() {
        return unitsMesure;
    }

    public void setUnitsMesure(String unitsMesure) {
        this.unitsMesure = unitsMesure.toUpperCase();
    }

    public String getEditBlocked() {
        return editBlocked;
    }

    public void setEditBlocked(String editBlocked) {
        this.editBlocked = editBlocked;
    }

    public String getPartClass() {
        return partClass;
    }

    public void setPartClass(String partClass) {
        this.partClass = partClass;
    }

    public String getPartCommodity() {
        return partCommodity;
    }

    public void setPartCommodity(String partCommodity) {
        this.partCommodity = partCommodity;
    }

    public String getConfirmCascadeDelete() {
        return confirmCascadeDelete;
    }

    public void setConfirmCascadeDelete(String confirmCascadeDelete) {
        this.confirmCascadeDelete = confirmCascadeDelete;
    }

    public String getShowConfirmCascadeDelete() {
        return showConfirmCascadeDelete;
    }

    public void setShowConfirmCascadeDelete(String showConfirmCascadeDelete) {
        this.showConfirmCascadeDelete = showConfirmCascadeDelete;
    }

    public String getSupplierClass() {
        return supplierClass;
    }

    public void setSupplierClass(String supplierClass) {
        this.supplierClass = supplierClass;
    }

    public String getSupplierCode() {
        return supplierCode;
    }

    public void setSupplierCode(String supplierCode) {
        this.supplierCode = supplierCode.toUpperCase();
    }

    public String getDateInMax() {
        return dateInMax;
    }

    public void setDateInMax(String dateInMax) {
        this.dateInMax = dateInMax;
    }

    public String getDateInMin() {
        return dateInMin;
    }

    public void setDateInMin(String dateInMin) {
        this.dateInMin = dateInMin;
    }

    public String getDateOutMax() {
        return dateOutMax;
    }

    public void setDateOutMax(String dateOutMax) {
        this.dateOutMax = dateOutMax;
    }

    public String getDateOutMin() {
        return dateOutMin;
    }

    public void setDateOutMin(String dateOutMin) {
        this.dateOutMin = dateOutMin;
    }

    public String getSelectedRowNum() {
        return selectedRowNum;
    }

    public void setSelectedRowNum(String selectedRowNum) {
        this.selectedRowNum = selectedRowNum;
    }

    public String getLowCom() {
        return lowCom;
    }

    public void setLowCom(String lowCom) {
        if(lowCom!=null)
            this.lowCom = lowCom.toUpperCase();
        else
            this.lowCom = null;
    }

    public String getPartClassFind() {
        return partClassFind;
    }

    public void setPartClassFind(String partClassFind) {
        this.partClassFind = partClassFind;
    }

}
